package com.zj.httpdemo.http.get;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by Lenovo on 2017/5/12.
 */

public class StringTask extends AsyncTask<String, Void, Void> {
    private static final String TAG = StringTask.class.getSimpleName();

    @Override
    protected Void doInBackground(String... params) {
        Log.e(TAG, "doInBackground: url = " + params[0]);

        HttpsURLConnection httpURLConnection = null;

        InputStream inputStream = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            URL url = new URL(params[0]);
            httpURLConnection = (HttpsURLConnection) url.openConnection();

            httpURLConnection.connect();

            if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) {

                inputStream = httpURLConnection.getInputStream();
                isr = new InputStreamReader(inputStream, "UTF-8");
                br = new BufferedReader(isr);

                String line;
                while ((line = br.readLine()) != null) {
                    Log.e(TAG, "doInBackground: line = " + line);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Log.e(TAG, "doInBackground: end");
        return null;
    }
}
